import Vue from 'vue'

import Router from 'vue-router'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import(/* webpackChunkName: "login_home_welcome" */'./components/Login')
    },
    {
      path: '/home',
      name: 'Home',
      component: () => import(/* webpackChunkName: "login_home_welcome" */'./components/Home'),
      redirect: '/welcome',
      children: [
        {
          path: '/welcome',
          name: 'Welcome',
          component: () => import(/* webpackChunkName: "login_home_welcome" */'./components/Welcome')
        },
        {
          path: '/users',
          name: 'Users',
          component: () => import(/* webpackChunkName: "users_rights_roles" */'./components/User')
        },
        {
          path: '/rights',
          name: 'Rights',
          component: () => import(/* webpackChunkName: "users_rights_roles" */'./components/Power')
        },
        {
          path: '/roles',
          name: 'Roles',
          component: () => import(/* webpackChunkName: "users_rights_roles" */'./components/Roles')
        },
        {
          path: '/categories',
          name: 'Goods',
          component: () => import(/* webpackChunkName: "categories_params" */'./components/Goods')
        },
        {
          path: '/params',
          name: 'Params',
          component: () => import(/* webpackChunkName: "categories_params" */'./components/Params')
        },
        {
          path: '/goods',
          name: 'GoodsList',
          component: () => import(/* webpackChunkName: "goods_add" */'./components/GoodsList')
        },
        {
          path: '/goods/add',
          name: 'Add',
          component: () => import(/* webpackChunkName: "goods_add" */'./components/GoodsList/add')
        },
        {
          path: '/orders',
          name: 'Orders',
          component: () => import(/* webpackChunkName: "orders_reports" */'./components/Order')
        },
        {
          path: '/reports',
          name: 'Reports',
          component: () => import(/* webpackChunkName: "orders_reports" */'./components/Report')
        }
      ]
    }
  ],
  mode: 'history'
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to: 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数,表示放行,next() 放行; next('/login') 强制跳转
  if (to.path === '/login') {
    // 一定要return,不让即使满足条件,还是会执行下面代码
    return next()
  }

  const token = window.sessionStorage.getItem('token')
  if (!token) {
    return next('/login')
  }
  next()
})

export default router
